package com.example.android.fragments

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.*
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import com.example.android.activities.MainActivity
import com.example.android.R
import com.example.android.activities.LoginActivity
import com.example.android.extensions.*
import com.example.android.models.User
import com.example.android.utils.models.MyResult
import com.example.android.viewmodels.SharedViewModel
import com.google.android.material.navigation.NavigationView
import com.mxn.soul.flowingdrawer_core.FlowingDrawer
import kotlinx.coroutines.delay
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * @ClassName SidebarFragment
 * @Author Ryan Kamanri
 * @Date 2022/6/1
 * @Description
 **/
class SidebarFragment : Fragment() {

    private val _Model : SharedViewModel by activityViewModels()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_sidebar, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        lifecycleScope.launch {

            val nav = view.findViewById<NavigationView>(R.id.side_bar_nav_view)

            InitNavHeader(nav)

            AddMenuItem(nav)

            AddMenuEvents(nav)

            Services.SharedService.GetSelfInfo(_Model)


        }

    }

    private fun InitNavHeader(nav: NavigationView) {
        val headerView = nav.getHeaderView(0)
        val headImage = headerView.findViewById<ImageView>(R.id.nav_header_image_view)

        headImage.setImageResource(R.drawable.head_img)

        //val model: SelectBedViewModel by viewModels()
        _Model.getSelf().observe(this, Observer<User>{ user ->
            // update UI
            val title = headerView.findViewById<TextView>(R.id.nav_header_title)
            val cotitle = headerView.findViewById<TextView>(R.id.nav_header_cotitle)
            title.text = user.name
            cotitle.text = user.userName

        })




    }

    private suspend fun AddMenuItem(nav: NavigationView) {
        // Add menu item here
        val menuIdListResult = Services.SidebarService.GetMenuList()
        val menuFrom = Services.Menu
        when(menuIdListResult.Code) {
            MyResult.OK -> {
                menuIdListResult.Data?.forEach {
                    nav.menu.AddItem(menuFrom, it)
                }
            }
        }
        // 退出登录选项(默认)
        nav.menu.AddItem(menuFrom, R.id.nav_log_out)
    }

    private fun AddMenuEvents(nav: NavigationView) {
        val baseTitle = (requireActivity() as MainActivity).Toolbar.title
        val toolbar = (requireActivity() as MainActivity).Toolbar

        // 点击顶部打开侧边栏
        toolbar.setOnClickListener {
            requireActivity().findViewById<FlowingDrawer>(R.id.main_drawer_layout).openMenu()
        }
        // Add Events here
        nav.setNavigationItemSelectedListener {
            lifecycleScope.launch {
                when (it.itemId) {
                    R.id.nav_announce -> {
                        TurnToFragment((requireActivity() as MainActivity).AnnounceFragment)
                        toolbar.title = "${getString(R.string.menu_announce)} - $baseTitle"
                    }


                // added by Lucas, 2022/6/9
                // check the bed
                R.id.nav_select_bed -> {
                    lifecycleScope.launch(Dispatchers.Main) {
                        Log.d(toString(), "asd")
                        val data = Services.SelectBedService.Check()
                        Log.d(toString(),data.toString())
                        if(data.Code == MyResult.OK){
                            TurnToFragment((requireActivity() as MainActivity).SelectBedFinishFragment)
                            toolbar.title = "${getString(R.string.menu_select_bed)} - $baseTitle"
                        }
                        else{
                            TurnToFragment((requireActivity() as MainActivity).SelectBedFragment)
                            toolbar.title = "${getString(R.string.menu_select_bed)} - $baseTitle"
                        }

                    }


                }

                    R.id.nav_online_payment -> {
                        TurnToFragment((requireActivity() as MainActivity).OnlinePaymentFragment)
                        toolbar.title = "${getString(R.string.menu_online_payment)} - $baseTitle"
                    }

                    R.id.nav_self_info -> {
                        TurnToFragment((requireActivity() as MainActivity).SelfInfoFragment)
                        toolbar.title = "${getString(R.string.menu_self_info)} - $baseTitle"

                    }

                    R.id.nav_online_chat -> {
                        TurnToFragment((requireActivity() as MainActivity).OnlineChatFragment)
                        toolbar.title = "${getString(R.string.menu_online_chat)} - $baseTitle"
                    }

                    R.id.nav_log_out -> {
                        Logout()
                    }
                }
            }
            true
        }
    }

    private suspend fun TurnToFragment(fragment: Fragment) {

        // close menu
        requireActivity().findViewById<FlowingDrawer>(R.id.main_drawer_layout).closeMenu()

        // clear refresh event
        (requireActivity() as MainActivity).SetOnRefreshSuspend {  }
        (requireActivity() as MainActivity).SetCheckCanDoRefresh { false }

        // pop backstacks
        val count = requireActivity().supportFragmentManager.backStackEntryCount
        Log.d(toString(), "Fragment Count: $count")
        for(i in 0 until count) {
            requireActivity().supportFragmentManager.popBackStack()
            delay(1000)
        }

        requireActivity()
            .supportFragmentManager
            .beginTransaction()
            .setCustomAnimations(R.anim.fragment_menu_select_in, R.anim.fragment_menu_select_out)
            .replace(R.id.content_main_fragment, fragment)
            .commit()


    }

    private fun Logout() {
        AlertDialog {
            it.SetContent("是否要退出登录?")
                .SetOnSureButton {
                    it.dismiss()
                    lifecycleScope.launch {
                        Services.SidebarService.Logout()
                    }
                    startActivity(Intent(context, LoginActivity::class.java))
                    requireActivity().finish()

                }
                .SetOnCancelButton {
                    it.dismiss()
                }
        }
    }


}